package com.qunar.wan.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.qunar.wan.AppConfig;
import com.qunar.wan.common_api.DateUtil;
import com.qunar.wan.common_api.model.User;
import com.qunar.wan.common_api.service.UserService;
import com.qunar.wan.web.controller.common.AbstractController;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * User: tongjie.yang Date: 13-11-27 Time: 上午10:45
 */
@Controller
@RequestMapping("user")
public class UserController extends AbstractController {
    @Resource
    private UserService userService;

    /**
     * 默认的活动达人数量 5
     */
    private final static int STARUSER_NUM = 5;

    /**
     * 接受QSSO的token值
     *
     * @param token
     * @param response
     * @return
     * @throws Exception
     */
    @Deprecated
    @RequestMapping("/QSSOCallBack")
    @ResponseBody
    public ModelAndView login(@RequestParam String token, String currpage, HttpServletResponse response)
            throws Exception {
        Preconditions.checkNotNull(token);
        //TODO
//        String userName = QSSO.getUser(token);
        String userName = "";
        userName = getQssoGivenName(userName);
        logger.info("用户{}于{}登录系统，跳转至：{}", userName, DateUtil.parse2ymdhms(new Date()),
                StringUtils.isEmpty(currpage) ? "index" : currpage);
        User user = userService.loginHandler(userName);
        // 将用户名和ID,isFirst加密，放入Cookie
        userService.writeUserCookie(user);
        return new ModelAndView("jump", "page", currpage);
    }

    /**
     * 根据用户ID查询
     */
    @RequestMapping("/showUser")
    public Object getUserById(@RequestParam String userId, HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        Preconditions.checkNotNull(userId);
        int id = Integer.parseInt(userId);
        User user = userService.selectUserById(id);
        Map<String, Object> map = Maps.newHashMap();
        map.put("user", user);
        map.put("flag", false);
        map.put("isLogin", false);

        if (userService.currentLogonUser().getUserName() != null/* loginState(request) */) {
            map.put("flag", true); // flag标示要显示的用户是否是操作者本人
            map.put("isLogin", false);
            if (judgeIdByCookie(userId, request)) {
                map.put("isLogin", true);
            }
        }
        return dataJson(map, System.currentTimeMillis() - startTime);
    }

    /**
     * 用户修改头像
     *
     * @param imgName
     * @param request
     * @return
     */
    @RequestMapping("/updateHeadImg")
    @ResponseBody
    public Object updateHeadImg(@RequestParam String imgName, HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        Preconditions.checkNotNull(imgName);
        userService.updateUserHeadImg(Preconditions.checkNotNull(userService.currentLogonUser()).getId(), imgName);
        return dataJson("上传成功！", System.currentTimeMillis() - startTime);

    }

    /**
     * 查询活动达人
     */
    @RequestMapping("/showStarUser")
    @ResponseBody
    public Object getStarUser() {
        long startTime = System.currentTimeMillis();
        List<User> list = userService.selectStarUser(STARUSER_NUM);
        return dataJson(list, System.currentTimeMillis() - startTime);
    }

    /**
     * 判断用户是否已经登录
     */
    @RequestMapping("/isLogin")
    @ResponseBody
    public Object judgeLoginState(HttpServletRequest request, HttpServletResponse response) throws Exception {
        long startTime = System.currentTimeMillis();
        String userName = Preconditions.checkNotNull(userService.currentLogonUser()).getUserName();
        Map<String, Object> map = Maps.newHashMap();
        String first = userService.getIsFirst();
        if (StringUtils.isEmpty(userName)) {
            map.put("isLogin", false);
            map.put("first", false);
            return dataJson(map, System.currentTimeMillis() - startTime);
        }
        User user = userService.selectUserByName(userName);
        map.put("isLogin", user != null);
        map.put("first", Boolean.parseBoolean(first));
        map.put("user", user);
        if (!StringUtils.isEmpty(first) && "false".equals(first)) {
            return dataJson(map, System.currentTimeMillis() - startTime);
        }
        user.setIsFirstLogon(false);
        userService.writeUserCookie(user);
        return dataJson(map, System.currentTimeMillis() - startTime);
    }

    /**
     * 用户退出
     *
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public Object logout(HttpServletRequest request, HttpServletResponse response) {
        long startTime = System.currentTimeMillis();
        logger.info("{}用户于{}退出", Preconditions.checkNotNull(userService.currentLogonUser()).getUserName(), DateUtil.parse2ymdhms(new Date()));
        userService.emptyUserCookie();
        return dataJson("true", System.currentTimeMillis() - startTime);
    }

    /**
     * 判断传入的id和用户Cookie中的id是否一致
     *
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    private boolean judgeIdByCookie(String id, HttpServletRequest request) {
        Preconditions.checkNotNull(id);
        String userId = userService.currentLogonUser().getId()+"";
        return id.equals(userId);
    }

    /**
     * 在QSSO接口上获取用户汉语名字
     *
     * @param userName
     * @return
     */
    @Deprecated
    private String getQssoGivenName(String userName) {
        String givenName = "";
        BufferedReader in = null;
        try {
            String url = AppConfig.getItem("qsso.url", "") + userName;
            String result = "";
            URL U = new URL(url);
            URLConnection connection = U.openConnection();
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            jsonObject = (JSONObject) jsonObject.get("message");
            givenName = jsonObject.get("givenName").toString();
        } catch (Exception e) {
            logger.info("getQssoGivenName occured an exception {}", e);
            throw new RuntimeException();
        } finally {

            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                logger.info("io close ocured an exception ", e);
            }

        }
        return givenName;
    }

    @RequestMapping("/login")
    @ResponseBody
    public Object userLogin(@RequestParam String usernameOremail,@RequestParam String password){
        long start  = System.currentTimeMillis();
        User user= userService.identifyUser(usernameOremail,DigestUtils.md5Hex(password));
        if (user==null){
            return errorJson(501,"用户名/邮箱密码有误",System.currentTimeMillis()-start);
        }
        userService.writeUserCookie(user);
        return dataJson(user,System.currentTimeMillis());
    }

    @RequestMapping("/register")
    @ResponseBody
    public Object register(@RequestParam String username,@RequestParam String password,@RequestParam String confirmPassword,
                           @RequestParam String email){

        long start = System.currentTimeMillis();
        if (userService.selectUserByName(username)!=null){
            return errorJson(400,"用户名已经存在",System.currentTimeMillis()-start);

        }
        if (!password.equals(confirmPassword)){
            return errorJson(400,"密码不一致",System.currentTimeMillis()-start);
        }
        User user = new User();
        user.setUserName(username);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setEmail(email);
        userService.insertObj(user);
        return dataJson("注册成功",System.currentTimeMillis()-start);
    }
}
